<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\model\TaskModel;
use app\model\TaskSendImgModel;
use think\db\Query;
use think\facade\Env;
use think\facade\Filesystem;

class Task extends BaseController
{
    public function query()
    {
        $params = $this->request->param();
        $adminId = $this->request->userInfo->adminId;
        $taskModel = new TaskModel();
        $tableName = Env::get('DB_PREFIX').$taskModel->getName();
        if(!empty($params['status'])) {
            $taskModel = $taskModel->where($tableName.'.status', $params['status']);
        }
        if(!empty($params['send_content'])) {
            $taskModel = $taskModel->where('send_content', 'like','%'.$params['send_content'].'%');
        }

        if (!empty($params['username'])) {
            $username = trim($params['username']);
            empty($username) || $taskModel = $taskModel->hasWhere('user',function (Query $query) use($username){
                $query->where('username','like','%'.$username.'%');
            });
        }
        $list = $taskModel
            ->where($tableName.'.admin_id',$adminId )
            ->with([
            'sendImg',
            'backImg',
            'user' => function (Query $query) {
                $query->field('id,username');
            }
        ])->paginate([
            'list_rows' => $params['pageSize'],
            'page' => $params['pageNo']
        ]);
        return show_serve($list);
    }

    public function add()
    {
        $params = $this->request->param();
        $adminId = $this->request->userInfo->adminId;
        $taskModel = TaskModel::create([
            'send_content' => $params['content'],
            'status' => 1,
            'user_id' => $params['user_id'],
            'admin_id' => $adminId
        ]);

        $imgUpdateList = [];
        foreach ($params['upload'] as $imgItem) {
            $imgUpdateList[] = [
                'id' => $imgItem['response']['id'],
                'task_id' => $taskModel->id
            ];
        }

        $taskSendImgModel = new TaskSendImgModel();
        $taskSendImgModel->saveAll($imgUpdateList);

        return show_serve();
    }

    public function changeStatus()
    {
        $params = $this->request->param();
        $taskModel = TaskModel::find($params['id']);
        if ($taskModel->status === 4) {
            return show_serve([],'已完成不可修改',1);
        }

        if ($params['status'] === 4) {
            //
            $taskModel->finish_time = time();
        } else {
            if ($taskModel->finish_time !== 0) {
                $taskModel->finish_time = 0;
            }
        }
        $taskModel->status = $params['status'];
        $taskModel->save();
        return show_serve();
    }

    public function del()
    {
        $params = $this->request->param();
        TaskModel::destroy($params['id']);
        return show_serve();
    }



}